package me.zhengjie.modules.system.service.impl;/*
*  Copyright 2019-2025 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alipay.api.domain.GoodInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.dto.PokerAwardQueryCriteria;
import me.zhengjie.modules.system.mapper.PokerActivateInfoMapper;
import me.zhengjie.modules.system.mapper.PokerAwardMapper;
import me.zhengjie.modules.system.mapper.PokerUserActivatInfoMapper;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.utils.CheckOnlineUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.util.*;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author greazy
* @date 2025-04-08
**/
@Service
@RequiredArgsConstructor
public class PokerAwardServiceImpl extends ServiceImpl<PokerAwardMapper, PokerAward> implements PokerAwardService {

    private final RconServiceImpl rconService;

    private final PokerAwardMapper pokerAwardMapper;

    private final PokerServerService serverService;

    private final PokerGoodInfoService goodService;

    private final UserService userService;

    private final PokerUserServerInfoService userServerInfoService;

    private final KingTeamService kingTeamService;

    private final PokerActivateInfoMapper activateInfoMapper;

    private final PokerUserActivatInfoMapper pokerUserActivatInfoMapper;

    private final UserActionLogService userActionLogService;

    @Override
    public PageResult<PokerAward> queryAll(PokerAwardQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(pokerAwardMapper.findAll(criteria, page));
    }

    @Override
    public List<PokerAward> queryAll(PokerAwardQueryCriteria criteria){
        return pokerAwardMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PokerAward resources) {
        pokerAwardMapper.insert(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PokerAward resources) {
        PokerAward pokerAward = getById(resources.getId());
        pokerAward.copy(resources);
        pokerAwardMapper.updateById(pokerAward);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        pokerAwardMapper.deleteBatchIds(ids);
    }

    @Override
    public void download(List<PokerAward> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PokerAward pokerAward : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("玩家id", pokerAward.getUserId());
            map.put("steam_id", pokerAward.getSteamId());
            map.put("物品id", pokerAward.getGoodId());
            map.put("奖励数量", pokerAward.getNum());
            map.put("物品名称", pokerAward.getGoodName());
            map.put("活动流水号", pokerAward.getTaskId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional
    public ResponseEntity<Object> wtq(Integer serverId, String goodId, Integer num) {
        //物品转筹码
        PokerServer server = serverService.getById(serverId);
        LambdaQueryWrapper<PokerGoodInfo> goodWrapper = new LambdaQueryWrapper<>();
        goodWrapper.eq(PokerGoodInfo::getGoodId,goodId);
        PokerGoodInfo good = goodService.getOne(goodWrapper);
        Long userId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(userId);
//        if (!CheckOnlineUtil.check(server.getIpAddr(),server.getPortAddr(),user.getSteamId(),server.getPasswordRcon())){
//            return new ResponseEntity<>("当前玩家不在线，请稍后重试", HttpStatus.ACCEPTED);
//        }
        LambdaQueryWrapper<PokerUserServerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PokerUserServerInfo::getServerId,serverId).eq(PokerUserServerInfo::getUserId,userId);
        PokerUserServerInfo userServer = userServerInfoService.getOne(wrapper);
        String response = rconService.sendCommond(server.getIpAddr(), server.getPortAddr(), server.getPasswordRcon(), "delitem ", user.getSteamId(), goodId, num);
        if (response.contains("Deleted")){
            String regex = "(\\d+)x";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(response);
            int number = 0;
            if (matcher.find()) {
                number = Integer.parseInt(matcher.group(1));
                if (number<=0){
                    return new ResponseEntity<>("已经没有啦",HttpStatus.ACCEPTED);
                }
            }
            Integer jettonNum = userServer.getJettonNum();
            userServer.setJettonNum(userServer.getJettonNum()+(good.getJettonNum()*number));
            userServerInfoService.updateById(userServer);
            //记录日志
            UserActionLog userActionLog = new UserActionLog();
            userActionLog.setActionType(1);
            userActionLog.setUserName(user.getUsername());
            userActionLog.setUserId(user.getId());
            userActionLog.setActivateId(null);
            userActionLog.setSteamId(user.getSteamId());
            String content = String.format("%s服务器存入了%s个%s,账户原便便余额:%s,本次增加便便%s个,现有便便余额为%s",
                    server.getName(),
                    number,
                    good.getGoodName(),
                    jettonNum,
                    good.getJettonNum() * number,
                    userServer.getJettonNum()
            );
            userActionLog.setContent(content);
            userActionLog.setCreatedTime(new Date());
            userActionLogService.save(userActionLog);


            return new ResponseEntity<>("根据您背包的数量，成功存入"+good.getJettonNum()*number+"个便便，请核验。",HttpStatus.ACCEPTED);
        }else if(response.contains("Failed to find player by UserId")){
            return new ResponseEntity<>("玩家当前不在线，请确认",HttpStatus.ACCEPTED);
        }
        else{
            return new ResponseEntity<>("材料不足，请确认数量",HttpStatus.ACCEPTED);

        }
    }

    @Override
    public ResponseEntity<Object> qtw(Integer serverId, String goodId, Integer num) {
        //筹码转物品
        PokerServer server = serverService.getById(serverId);
        LambdaQueryWrapper<PokerGoodInfo> goodWrapper = new LambdaQueryWrapper<>();
        goodWrapper.eq(PokerGoodInfo::getGoodId,goodId);
        PokerGoodInfo good = goodService.getOne(goodWrapper);
        Long userId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(userId);
//        if (!CheckOnlineUtil.check(server.getIpAddr(),server.getPortAddr(),user.getSteamId(),server.getPasswordRcon())){
//            return new ResponseEntity<>("当前玩家不在线，请稍后重试", HttpStatus.ACCEPTED);
//        }
        LambdaQueryWrapper<PokerUserServerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PokerUserServerInfo::getServerId,serverId).eq(PokerUserServerInfo::getUserId,userId);
        PokerUserServerInfo userServer = userServerInfoService.getOne(wrapper);
        if (userServer.getJettonNum()-(good.getJettonNum()*num)>=0){
            String response = rconService.sendCommond(server.getIpAddr(),server.getPortAddr(),server.getPasswordRcon(),"give ",user.getSteamId(),goodId,num);
            if (response.contains("Gave")){
                Integer jettonNum = userServer.getJettonNum();
                userServer.setJettonNum(userServer.getJettonNum()-(good.getJettonNum()*num));
                userServerInfoService.updateById(userServer);
                //记录日志
                UserActionLog userActionLog = new UserActionLog();
                userActionLog.setActionType(2);
                userActionLog.setUserName(user.getUsername());
                userActionLog.setUserId(user.getId());
                userActionLog.setActivateId(null);
                userActionLog.setSteamId(user.getSteamId());
                String content = String.format("%s服务器提取了%s个%s,账户原便便余额:%s,本次共消耗便便%s个,现有便便余额为%s",
                        server.getName(),
                        num,
                        good.getGoodName(),
                        jettonNum,
                        good.getJettonNum() * num,
                        userServer.getJettonNum()
                );
                userActionLog.setContent(content);
                userActionLog.setCreatedTime(new Date());
                userActionLogService.save(userActionLog);

                return new ResponseEntity<>("成功取出"+num+"个该素材",HttpStatus.ACCEPTED);
            }else if(response.contains("Failed to find player by UserId")){
                return new ResponseEntity<>("玩家当前不在线，请确认",HttpStatus.ACCEPTED);
            }else {
                return new ResponseEntity<>("兑换异常，请联系管理员重试",HttpStatus.ACCEPTED);
            }
        }
        else{
            return new ResponseEntity<>("兑换失败，余额不足",HttpStatus.ACCEPTED);

        }
    }

    @Override
    public ResponseEntity<Object> s(Integer awardId ) {
        Long userId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(userId);
        //获取奖励
        PokerAward award = this.getById(awardId);
        PokerServer server = serverService.getById(award.getServerId());

        //记录日志
        UserActionLog userActionLog = new UserActionLog();
        userActionLog.setActionType(3);
        userActionLog.setUserName(user.getUsername());
        userActionLog.setUserId(user.getId());
        userActionLog.setSteamId(user.getSteamId());
        userActionLog.setCreatedTime(new Date());



        if (user.getId().equals(award.getUserId())){
            //如果获取的物品是平台便便，直接增加账户信息即可
            if (award.getGoodId().equals("ping_tai_glod")){
                LambdaQueryWrapper<PokerUserServerInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(PokerUserServerInfo::getUserId,userId).eq(PokerUserServerInfo::getServerId,server.getId());
                PokerUserServerInfo userServer = userServerInfoService.getOne(wrapper);
                Integer jettonNum = userServer.getJettonNum();
                userServer.setJettonNum(userServer.getJettonNum()+award.getNum().intValue());
                userServerInfoService.updateById(userServer);
                award.setIsEnd(1);
                this.updateById(award);

                userActionLog.setActivateId(null);
                String content = String.format("%s:%s服务器领取奖励，%s个便便,账户原便便余额:%s,本次领取了便便%s个,现有便便余额为%s",
                        award.getActivateName(),
                        server.getName(),
                        award.getNum(),
                        jettonNum,
                        award.getNum(),
                        userServer.getJettonNum()
                );
                userActionLog.setContent(content);
                userActionLog.setCreatedTime(new Date());
                userActionLogService.save(userActionLog);

                return new ResponseEntity<>("奖励发放成功",HttpStatus.ACCEPTED);
            }
            //活动便便池比例奖励
            else if(award.getGoodId().equals("jiang_chi_glod")){
                //todo  注意区分扑克和国王排名游戏的两种 奖励便便池  。 增加到平台便便账户

                QueryWrapper<PokerActivateInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("task_id",award.getTaskId());
                PokerActivateInfo activateInfo = activateInfoMapper.selectOne(wrapper);
                LambdaQueryWrapper<PokerUserServerInfo> UserServerWrapper = new LambdaQueryWrapper<>();
                UserServerWrapper.eq(PokerUserServerInfo::getUserId,userId).eq(PokerUserServerInfo::getServerId,server.getId());
                PokerUserServerInfo userServer = userServerInfoService.getOne(UserServerWrapper);
                Integer bianbianNum = 0;
                Integer totalNum =0;
                Integer userFontJettnum =0;
                Integer userAfterJettnum =0;
                //德州扑克活动
                if (activateInfo.getActivateType().equals(0)){
                    LambdaQueryWrapper<PokerUserActivatInfo> usersWrapper = new LambdaQueryWrapper<>();
                    usersWrapper.eq(PokerUserActivatInfo::getTaskId,activateInfo.getTaskId()).eq(PokerUserActivatInfo::getActivateId,activateInfo.getId())
                            .orderByAsc(PokerUserActivatInfo::getRank);
                    List<PokerUserActivatInfo> userActivatInfoList = pokerUserActivatInfoMapper.selectList(usersWrapper);

                    int total = userActivatInfoList.stream()
                            .mapToInt(PokerUserActivatInfo::getTotalPayJettonNum)
                            .sum();
                    totalNum= total;
                    double numdouble = award.getNum()*total;
                    Integer num  = (int)numdouble;
                    bianbianNum = num;
                    userFontJettnum =  userServer.getJettonNum();
                    userServer.setJettonNum(userServer.getJettonNum()+num);
                    userAfterJettnum =  userServer.getJettonNum();

                }
                //国王排名
                else if(activateInfo.getActivateType().equals(1)){
                    LambdaQueryWrapper<KingTeam> teamWrapper = new LambdaQueryWrapper<>();
                    teamWrapper.eq(KingTeam::getActivateId,activateInfo.getId());
                    List<KingTeam> teamList = kingTeamService.list(teamWrapper);
                    Integer groupTotalBianBian = teamList.stream().mapToInt(KingTeam::getBianbianVal).sum();
                    double numdouble= award.getNum()*groupTotalBianBian;
                    Integer num  = (int) numdouble;
                    bianbianNum = num;
                    totalNum= groupTotalBianBian;
                    userFontJettnum =  userServer.getJettonNum();
                    userServer.setJettonNum(userServer.getJettonNum()+num);
                    userAfterJettnum =  userServer.getJettonNum();

                }
                userServerInfoService.updateById(userServer);
                award.setIsEnd(1);
                this.updateById(award);


                userActionLog.setActivateId(null);
//                userActionLog.setTaskId(award.getTaskId());
                String content = String.format("%s:%s服务器领取奖励,总奖池为:%s,账户原便便余额:%s,本次领取了便便%s个,现有便便余额为%s",
                        award.getActivateName(),
                        server.getName(),
                        totalNum,
                        userFontJettnum,
                        bianbianNum,
                        userAfterJettnum
                );
                userActionLog.setContent(content);
                userActionLog.setCreatedTime(new Date());
                userActionLogService.save(userActionLog);
                return new ResponseEntity<>("奖池比例已经发放",HttpStatus.OK);

            }
            //经验值 直接增加账户经验值
            else if(award.getGoodId().equals("empirical_val")){
                Integer empiricalVal = user.getEmpiricalVal();
                user.setEmpiricalVal(user.getEmpiricalVal()+award.getNum().intValue());
                try {
                    userService.updateDesc(user);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                award.setIsEnd(1);
                this.updateById(award);

                String content = String.format("%s:领取奖励,账户原经验值:%s,本次领取经验值%s,当前经验值%s",
                        award.getActivateName(),
                        empiricalVal,
                        award.getNum(),
                        user.getEmpiricalVal()
                );
                userActionLog.setContent(content);
                userActionLog.setCreatedTime(new Date());
                userActionLogService.save(userActionLog);
                return new ResponseEntity<>("经验值已增加",HttpStatus.OK);

            }else{
                //其余情况均为游戏材料，cron通信领取
                String response = rconService.sendCommond(server.getIpAddr(), server.getPortAddr(), server.getPasswordRcon(), "give ", award.getSteamId(), award.getGoodId(), award.getNum().intValue());
                if (response.contains("Gave")){
                    award.setIsEnd(1);
                    this.updateById(award);
                    String content = String.format("%s:%s服务器领取奖励,领取%s个%s",
                            award.getActivateName(),
                            server.getName(),
                            award.getNum(),
                            award.getGoodName()

                    );
                    userActionLog.setContent(content);
                    userActionLog.setCreatedTime(new Date());
                    userActionLogService.save(userActionLog);
                    return new ResponseEntity<>("奖励发放成功",HttpStatus.ACCEPTED);
                }else if(response.contains("Failed to find player by UserId")){
                    return new ResponseEntity<>("玩家当前不在线，请确认",HttpStatus.ACCEPTED);
                }else {
                    return new ResponseEntity<>("奖励发放失败，请联系管理员", HttpStatus.ACCEPTED);
                }
            }
        }else{
            return new ResponseEntity<>("非法领取", HttpStatus.ACCEPTED);
        }

    }
}